<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Excel类
 * 
 * @author  : $Author: spike $
 * @date    : $Date: 2013-12-31 11:49:44 +0800 (二, 2013-12-31) $
 * @version : $Id: excel_model.php 18 2013-12-31 03:49:44Z spike $
 * @rev     : $Revision: 18 $
 */
class Excel_model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();

        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/IOFactory');
    }

    public function number_to_column_name($number)
    {
        $abc     = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $abc_len = strlen($abc);

        $result = "";
        $tmp    = $number;

        while($number > $abc_len) 
        {
            $remainder = $number % $abc_len;
            $result    = $abc[$remainder-1].$result;
            $number    = floor($number / $abc_len);
        }
        return $abc[$number-1].$result;
    }

    /**
     * [导出excel模版]
     */
    public function export( & $data, $title = NULL, $filename = NULL, $format = 'xls')
    {
        $title    = (string)$title;
        $filename = (string)$filename;
        if( ! is_array($data) )
        {
            $this->set_error("导出Excel失败：数据必须是一个数组。");
            return FALSE;
        }

        $login_info = login_info();
        $this->load->model('Rbac_model');
        $this->Rbac_model->wrap_admin_info($login_info);
        $admin = (string)$login_info['admin_info']['nickname'];

        $excel = new PHPExcel();
        $excel->setActiveSheetIndex(0);

        $excel->getProperties()
              ->setCreator($admin)
              ->setLastModifiedBy($admin)
              ->setTitle($title);

        if( ! empty($title) )
        {
            $excel->getActiveSheet()->setTitle($title);
        }

        if($data)
        {
            $count = count($data);
            for($i = 0; $i < $count; $i++)
            {
                $row_number = $i+1;
                $col_number = 1;
                foreach ($data[$i] as $k => &$v) 
                {
                    $col_name = $this->number_to_column_name($col_number).$row_number;
                    $excel->getActiveSheet()->setCellValue($col_name, (string)$v);
                    $col_number++;
                }
                unset($v);
            }
        }
        
        $filename = empty($filename) ? uniqid() : $filename;

        switch (strtolower($format)) 
        {
            case 'xls':
            default:
                    header("Content-Type: application/vnd.ms-excel");
                    header("Content-Disposition: attachment;filename=\"{$filename}.xls\"");
                    header("Cache-Control: max-age=0");

                    $writer = IOFactory::createWriter($excel, 'Excel5');
                    $writer->save('php://output');
                break;
        }
        
    }

 }
